#!/usr/bin/python
"""A module for printing a Local Ordinance Title 24 Report to a PDF file.
Test this module by calling it like this:
    python /path/to/pdf.py
It will populate the MC-RES form with dummy data, generate a PDF file and
print the path to that PDF file.
"""


import os
import tempfile
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate
from settings import *
from title24_widgets import draw_footer
from title24_widgets import CoverPage


class PDF:
    """A class to generate a Title 24 Local Ordinance Report in PDF format.
    See the main() function for an example of what data can/should be
    passed in as keyword arguments (kwargs).
    """
    def __init__(self, **kwargs):
        self.kwargs = kwargs
        self.filename = kwargs.get(
            'filename',
            os.path.basename(tempfile.mktemp()),
        )

    def path_to_file(self):
        """Returns the full path to the PDF file"""
        return os.path.join(
            self.kwargs.get('render_dir', TEMP_DIR),
            self.filename,
        )

    def render(self):
        """Renders the PDF to disk"""
        kw = self.kwargs
        def my_first_page(canvas, doc):
            canvas.saveState()
            canvas.setAuthor(
                kw.get(
                    'doc_author_company_name',
                    'MISSING DOC_AUTHOR_COMPANY_NAME'
                )
            )
            canvas.setTitle(DOC_TITLE)
            canvas.setSubject(DOC_SUBJECT % \
                kw.get(
                    'project_title',
                    'MISSING PROJECT_TITLE'
                )
            )
            draw_footer(canvas, **kw)
            canvas.restoreState()

        def my_later_pages(canvas, doc):
            canvas.saveState()
            draw_footer(canvas, **kw)
            canvas.restoreState()

        doc = SimpleDocTemplate(
            self.path_to_file(),
            pagesize=letter,
            leftMargin=LEFT_MARGIN,
            rightMargin=RIGHT_MARGIN,
            topMargin=TOP_MARGIN,
            bottomMargin=BOTTOM_MARGIN,
            allowSplitting=False,
            showBoundary=DEBUG,
        )
        doc.build(
            kw['story'],
            onFirstPage=my_first_page,
            onLaterPages=my_later_pages
        )


def get_story(**kwargs):
    """Returns the story that will be rendered into a PDF file."""
    from reportlab.platypus import PageBreak
    import mcres
    pages = []
    pages.append(CoverPage(**kwargs))
    pages += mcres.get_flowables(**kwargs)
    story = []
    for page in pages:
        story.append(page)
        story.append(PageBreak())
    # Get rid of the last page break
    story.pop()
    return story


def render(**data):
    """Renders the PDF file and returns the path to the rendered file.
    data is a Python dictionary containing all the data rendered in the file.
    See this module's main function for an example of what dictionary keys are
    expected.
    Call it like this:
        from title24-local-ordinance.pdf import render
        data = dict(
            project_title='Foobar Testing Project Title',
            ...
            designer_name='Joe Doe Designer',
        )
        path_to_pdf_file = render(**data)
        print "pdf rendered to: %s" % path_to_pdf_file
    """
    data['story'] = get_story(**data)
    pdf = PDF(**data)
    pdf.render()
    return pdf.path_to_file()


def main():
    """Test rendering the PDF file.  Notice that most of the work is in creating
    the data dictionary, which is sent to the render function which initiates
    the heavy lifting of creating the PDF.
    """
    import datetime
    import tempfile
    data = dict(
        render_dir=tempfile.gettempdir(),
        filename='mcres_test_%s.pdf' \
            % datetime.datetime.now().strftime('%Y%m%d%H%M%s'),
        project_title='Foobar Testing Project Title',
        project_addr_formatted='012 Project Way\nProjectville, CA 87654',
        project_cfa=1234.5,
        doc_author_company_name='Foobar Testing Company',
        doc_author_name='Jim Doe DocAuthor',
        doc_author_addr_formatted='123 Doc Author Way\nMy Town, CA  98765',
        designer_company_name='Fizzbang Design',
        designer_name='Joe Doe Designer',
        designer_addr_formatted='456 Design Circle, Roundville, CA 31416',
        footer_left_text='left footer text',
        footer_center_text='center footer text',
        footer_right_text='right footer text',
        date_str=datetime.datetime.now().strftime(SHORT_DATE_FORMAT),
        standard_t24=1234.56,
        proposed_t24=950.0,
        adjustment_factor_standard=0.654,
        adjustment_factor_proposed=0.85,
        adjusted_standard_design=1234.56*0.654,
        max_allowed_proposed=950.0*0.85,
        annual_pv_production=2000.0,
        solar_pv_credit=(2000.0/(0.293*1234.5)),
        adjusted_proposed_design=(950.0-(1000.0/(0.293*1234.5)))
    )
    print "PDF rendered to: '%s'" % render(**data)


if __name__ == '__main__':
    main()
